package io.libp2p.example.chat;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpUtils {

    public static final String TAG = "HttpUtils";

    public interface GetIceServerCallback{
        void onIceServer(IceServerJson iceServerJson);
    }

    public static void startGet(GetIceServerCallback callback){
        new Thread(() -> getIceServer(callback)).start();

        //callback.onIceServer(null);
    }

    private static void getIceServer(GetIceServerCallback callback){
        try {
            String url = "https://innosz.voidtech.com.cn/usb-webrtc/api/ice_server/auth/liuwenlong";

            URL urlObj = new URL(url);

            HttpURLConnection conn = (HttpsURLConnection) urlObj.openConnection();

            if(url.startsWith("https")) {
                handleSSLHandshake((HttpsURLConnection)conn);
            }

            conn.setRequestMethod("GET");

            int responseCode = conn.getResponseCode();
            MyLog.D(TAG, "getIceServer responseCode="+responseCode);

            // 读取响应内容
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                MyLog.I(TAG, "getIceServer response="+response);

                IceServerJson serverJson = new Gson().fromJson(response.toString(), IceServerJson.class);

                callback.onIceServer(serverJson);
            }

            // 关闭连接
            conn.disconnect();
        } catch (Exception e) {
            MyLog.I(TAG, "getIceServer Exception="+e);
            e.printStackTrace();
        }
    }

    public static void handleSSLHandshake(HttpsURLConnection httpsURLConnection) {
        httpsURLConnection.setSSLSocketFactory(SSLSocketClient.getSSLSocketFactory());
        httpsURLConnection.setHostnameVerifier((hostname, session) -> true);
        MyLog.D(TAG,"handleSSLHandshake complete");
    }

}
